#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
from IPy import IP

'''
0 异常登录
1 加白地址或无登录
2 抛出
'''

white_ips= sys.argv[1] 
# zabbix传入ip列表
#white_ips = '10.0.0.0/8-172.16.0.0/16-192.168.0.1/16' 
result_str=os.popen("last |grep still|awk '{print $3}'").read() # 命令获取
#result_str = '192.168.66.10\n192.168.66.41\n' # 测试数据

def check_ip(ip):
    for white_ip_pool in white_ips.split("-"):
        try:
            white_ip_pool = IP(white_ip_pool, make_net=1)
            if ip in IP(white_ip_pool):
                res = 1  # 正常返回
                break
            else:
                # print("ip:%s 匹配失败网段:%s" % (ip, white_ip_pool))
                res = 0  # 异常返回
        except Exception as e:
            res = e
    return res


def main():
    if len(result_str)>7: 
        online_IP =  list(filter(None, result_str.split('\n'))) # 获取在线ip列表
        for host_ip in online_IP:
            result = check_ip(host_ip)
    else:
        result=1 # 没有异常登录
    print(result)


if __name__ == '__main__':
    main()
